<template>
  <div class="system-container">
    <vab-query-form>
      <el-form :inline="true" :model="queryForm" @submit.native.prevent>
        <el-form-item class="pr8">
          <el-date-picker
            v-model="queryForm.BEGIN_DATE"
            class="wd150"
            placeholder="开始日期"
            type="date"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="queryForm.END_DATE"
            class="wd150"
            placeholder="结束日期"
            type="date"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryForm.MATCH_SHEET_NUM"
            class="ml12 wd150"
            clearable
            placeholder="配血单号"
          />
        </el-form-item>
        <el-form-item class="pl12">
          <el-button icon="el-icon-search" type="primary" @click="queryData">
            查询
          </el-button>
          <el-button
            icon="el-icon-document-checked"
            style="float: right"
            type="success"
            @click="submit"
          >
            提交配血结果
          </el-button>
        </el-form-item>
      </el-form>
    </vab-query-form>
    <div class="h12"></div>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      :height="630"
      :row-class-name="tableRowClassName"
    >
      <el-table-column
        align="center"
        label="配血单号"
        prop="MATCH_SHEET_NUM"
        show-overflow-tooltip
        width="76"
      />
      <el-table-column
        align="center"
        label="申请单号"
        prop="APPLY_NUM"
        show-overflow-tooltip
        width="76"
      />
      <el-table-column
        align="center"
        label="科室"
        prop="DEPT_NAME"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        label="受血者"
        prop="PAT_NAME"
        show-overflow-tooltip
        width="60"
      />
      <el-table-column
        align="center"
        label="门诊号"
        prop="PATIENT_ID"
        show-overflow-tooltip
        width="75"
      />
      <el-table-column
        align="center"
        label="献血者"
        prop="NAME"
        show-overflow-tooltip
        width="60"
      />
      <el-table-column
        align="center"
        label="血员号"
        prop="BLOOD_DONOR_ID"
        show-overflow-tooltip
        width="75"
      />
      <el-table-column
        align="center"
        label="血液成分"
        prop="BLOOD_TYPE_NAME"
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        align="center"
        label="配血试管号"
        prop="BLOOD_ID_UP"
        show-overflow-tooltip
        width="90"
      />
      <el-table-column
        align="center"
        label="血袋号"
        prop="BLOOD_ID"
        show-overflow-tooltip
        width="80"
      />
      <el-table-column
        align="center"
        label="受血者血型/RHD"
        prop="PAT_BLOOD_GROUP"
        show-overflow-tooltip
        width="70"
      >
        <template #default="{ row }">
          {{ `${row.PAT_BLOOD_GROUP || ''} / ${row.PAT_RH}` }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="献血者血型/RHD"
        prop="BLOOD_GROUP"
        show-overflow-tooltip
        width="70"
      >
        <template #default="{ row }">
          {{ `${row.BLOOD_GROUP} / ${row.RH}` }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="储血量(U)"
        prop="BLOOD_CAPACITY"
        show-overflow-tooltip
        width="55"
      />
      <el-table-column
        align="center"
        :label="+bloodMatchTypePid === 2 ? '配血结果' : '子配血结果'"
        prop="blood.blood_group"
        width="130"
      >
        <el-table-column
          align="center"
          label="配血方式"
          prop="province"
          width="90"
        >
          <template #default="scope">
            <span
              v-for="(item, index) in scope.row.blood_match_types"
              :key="index"
              class="span-block"
            >
              {{ item.blood_match_type_name }}
            </span>
          </template>
        </el-table-column>
        <template v-if="+bloodMatchTypePid === 2">
          <el-table-column
            align="center"
            label="凝集强度"
            prop="AGGREGATION_INTENSITY"
            show-overflow-tooltip
            width="120"
          >
            <template #default="scope">
              <!-- <el-cascader
                v-for="(item, index) in scope.row.blood_match_types"
                :key="index"
                v-model="item.AGGREGATION_INTENSITY"
                clearable
                :options="bloodMatchSideOptions"
                size="mini"
                @change="handleChange(item,scope.row)"
              /> -->
              <el-select
                v-for="(item, index) in scope.row.blood_match_types"
                :key="index"
                v-model="item.AGGREGATION_INTENSITY"
                clearable
                filterable
                placeholder="凝集程度"
                size="mini"
                style="margin: 4px 0"
                @change="handleChange(item, scope.row, 'AGGREGATION_INTENSITY')"
              >
                <el-option
                  v-for="(citem, cindex) in bloodMatchSideOptionsXxb"
                  :key="index + cindex"
                  :label="citem.label"
                  :value="citem.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column align="center" label="主侧" prop="city" width="120">
            <template #default="{ row }">
              <el-select
                v-for="(item, index) in row.blood_match_types"
                :key="index"
                v-model="item.FIRST_RESULT"
                clearable
                filterable
                placeholder="主侧"
                size="mini"
                style="margin: 4px 0"
                @change="handleChange(item, row, 'FIRST_RESULT')"
              >
                <el-option
                  v-for="(citem, cindex) in bloodMatchSideOptions"
                  :key="index + cindex"
                  :label="citem.label"
                  :value="citem.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="次侧"
            prop="address"
            width="120"
          >
            <template #default="scope">
              <el-select
                v-for="(item, index) in scope.row.blood_match_types"
                :key="index"
                v-model="item.SECOND_RESULT"
                clearable
                filterable
                placeholder="次侧"
                size="mini"
                style="margin: 4px 0"
                @change="handleChange(item, scope.row, 'SECOND_RESULT')"
              >
                <el-option
                  v-for="(citem, cindex) in bloodMatchSideOptions"
                  :key="index + cindex"
                  :label="citem.label"
                  :value="citem.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </template>
        <el-table-column align="center" label="结果" prop="address" width="100">
          <template #default="scope">
            <el-select
              v-for="(item, index) in scope.row.blood_match_types"
              :key="'a' + index"
              v-model="item.MATCH_RESULT"
              clearable
              placeholder="结果"
              size="mini"
              style="margin: 4px 0"
              @change="handleResultChange(item, scope.row)"
            >
              <el-option
                v-for="(citem, cindex) in bloodMatchResult"
                :key="+cindex"
                :label="citem"
                :value="citem"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-if="+bloodMatchTypePid !== 2"
          align="center"
          label="操作"
          prop="address"
          width="80"
        >
          <template #default="scope">
            <div class="d-flex flex-column">
              <el-link
                icon="el-icon-plus"
                type="primary"
                @click="addItem(scope.row)"
              >
                添加
              </el-link>
              <el-link
                v-for="(item, index) in scope.row.blood_match_types"
                :key="index"
                icon="el-icon-delete"
                style="margin: 4px 0"
                type="danger"
                @click="delItem(scope.row, index)"
              >
                删除
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table-column>
      <!-- <el-table-column
        v-if="+bloodMatchTypePid !== 2"
        align="center"
        label="直抗"
        prop="address"
        width="120"
      >
        <template #default="{ row }">
          <el-cascader
            v-model="row.DAT"
            clearable
            :options="bloodMatchSideOptions"
            size="mini"
            style="margin: 4px 0"
          />
        </template>
      </el-table-column> -->
      <el-table-column
        v-if="+bloodMatchTypePid !== 2"
        align="center"
        label="配血结果"
        prop="MATCH_RESULT"
        show-overflow-tooltip
        width="116"
      >
        <template #default="scope">
          <el-select
            v-model="scope.row.MATCH_RESULT"
            clearable
            placeholder="配血结果"
            size="mini"
          >
            <el-option
              v-for="(item, index) in bloodMatchResult"
              :key="+index"
              :label="item"
              :value="item"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="配血时间"
        prop="MATCH_DATE"
        show-overflow-tooltip
        width="140"
      >
        <template #header>
          <div class="flex flex-column">
            <span>配血时间</span>
            <span>用血时间</span>
          </div>
        </template>
        <template #default="{ row }">
          <div class="flex flex-column">
            <span>{{ getDate(row.MATCH_DATE) }}</span>
            <span>{{ getDate(row.TRANS_DATE) }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import {
    PLAK0015 as getList,
    PLAK0016 as saveMatchResult,
  } from '@/api/client'
  import { mapGetters } from 'vuex'
  import {
    matchTypes,
    bloodMatchSideOptions,
    bloodMatchSideOptionsXxb,
    bloodMatchResult,
    bloodRhds,
    bloodResults,
  } from '@/utils/constant'
  import { getCurrentTime, filterList, convertArr2Obj } from '@/utils'
  import {
    getCurrentDate,
    getMatchTransClass,
    getNextDate,
  } from '@/utils/index'
  export default {
    name: 'Result',
    props: {
      activeName: {
        type: String,
        default() {
          return 'fourth'
        },
      },
    },
    data() {
      return {
        list: [],
        listLoading: true,
        selectRows: '',
        queryForm: {
          BEGIN_DATE: getCurrentDate(),
          END_DATE: getNextDate(getCurrentDate(), 1),
          MATCH_SHEET_NUM: '',
        },
        matchTypes,
        bloodMatchSideOptions,
        bloodMatchSideOptionsXxb,
        bloodMatchResult,
        bloodMatchTypeId: 1,
        bloodMatch: {},
        currentIndex: '',
        bloodMatchTypeIds: '',
        key: 'sally',
        bloodMatchTypesResult: [],
        bloodRhds,
        bloodResults,
      }
    },
    computed: {
      ...mapGetters({
        username: 'user/username',
        bloodMatchTypePid: 'initialData/bloodMatchTypePid',
        bloodMatchType: 'initialData/bloodMatchType',
        bloodMatchTypes: 'initialData/bloodMatchTypes',
      }),
      bloodMatchTypeFormat() {
        let arr = []
        this.bloodMatchTypes.forEach((item) => {
          arr = arr.concat(item.children)
        })
        const arrObj = convertArr2Obj(arr, 'id')
        let res = []
        this.bloodMatchType.forEach((item) => {
          res.push(arrObj[item.slice(-1)[0]])
        })
        return res
      },
      bloodMatchResultsFill() {
        return this.list.map((val) => {
          val.match_result = val.match_result || 1
          return val
        })
      },
    },
    watch: {
      activeName: {
        handler(newVal) {
          if (newVal === 'fourth') {
            this.$baseEventBus.$emit('reload-router-view')
            setTimeout(() => {
              this.fetchData()
            }, 100)
          }
        },
        immediate: true,
      },
      bloodMatchTypePid() {
        if (this.activeName === 'fourth') {
          this.$baseEventBus.$emit('reload-router-view')
          setTimeout(() => {
            this.fetchData()
          }, 100)
        }
      },
      // bloodMatchTypeFormat: {
      //   handler(newVal) {
      //     if (newVal) {
      //       let arr = []
      //       newVal.forEach((item) => {
      //         arr.push({
      //           blood_match_type_id: item.id,
      //           blood_match_type_name: item.name,
      //           FIRST_RESULT: '无凝集',
      //           SECOND_RESULT: '无凝集',
      //           AGGREGATION_INTENSITY: '无凝集',
      //           MATCH_RESULT: '相合',
      //         })
      //       })
      //       this.list = this.list.map((val) => {
      //         val.blood_match_types = JSON.parse(JSON.stringify(arr))
      //         return val
      //       })
      //     }
      //   },
      //   deep: true,
      //   immediate: true,
      // },
    },
    methods: {
      getDate(value) {
        if (value) {
          return value.substr(0, value.length - 3)
        }
        return ''
      },
      delItem(row, index) {
        if (row.blood_match_types.length > 1) {
          row.blood_match_types.splice(index, 1)
        }
      },
      addItem(row) {
        const bloodMatchTypes = this.bloodMatchTypes.filter((val) => {
          return val.id === this.bloodMatchTypePid
        })[0].children

        const blood_match_types_ids = row.blood_match_types.map(
          (val) => val.blood_match_type_id
        )
        const bloodMatchTypesFilter = bloodMatchTypes.filter((val) => {
          return !blood_match_types_ids.includes(+val.id)
        })
        if (bloodMatchTypesFilter.length > 0) {
          const item = bloodMatchTypesFilter[0]
          row.blood_match_types.push({
            blood_match_type_pid: this.bloodMatchTypePid,
            blood_match_type_id: item.id,
            blood_match_type_name: item.name,
            FIRST_RESULT: '',
            SECOND_RESULT: '',
            AGGREGATION_INTENSITY: '',
            MATCH_RESULT: '',
          })
        }
      },
      getBloodMatchFinished(items) {
        if (items && items.length > 0) {
          const itemsFinished = items.filter((val) => {
            return val.MATCH_RESULT
          })
          return items.length === itemsFinished.length
        }
        return false
      },
      showMatchTypes(row, index) {
        this.bloodMatch = row
        this.bloodMatchTypeIds = row.blood_match_type_ids
        this.bloodMatchTypeId = row.blood_match_type_ids[0]
        this.currentIndex = index
        this.key = Math.random()
      },
      queryData() {
        this.fetchData()
      },
      async fetchData() {
        this.queryForm.MATCH_OPERATOR = this.username
        this.listLoading = true
        const { data } = await getList(this.queryForm).catch(() => {
          this.listLoading = false
        })
        this.list = filterList(data, this.bloodMatchTypePid)
        let arr = []
        this.bloodMatchTypeFormat.forEach((item) => {
          arr.push({
            blood_match_type_pid: this.bloodMatchTypePid,
            blood_match_type_id: item.id,
            blood_match_type_name: item.name,
            FIRST_RESULT: '',
            SECOND_RESULT: '',
            AGGREGATION_INTENSITY: '',
            MATCH_RESULT: '',
          })
        })
        this.list = this.list.map((val) => {
          if (!val.blood_match_types || val.blood_match_types.length === 0) {
            val.blood_match_types = JSON.parse(JSON.stringify(arr))
            let cResultCount = 0
            val.blood_match_types.map((cval) => {
              if (val.MATCH_METCH.indexOf(cval.blood_match_type_name) > -1) {
                cval.FIRST_RESULT = val.FIRST_RESULT
                cval.SECOND_RESULT = val.SECOND_RESULT
                cval.MATCH_RESULT = val.MATCH_RESULT
                cResultCount++
              }
            })
            if (
              cResultCount === val.blood_match_types.length &&
              val.MATCH_RESULT === '相合'
            ) {
              val.MATCH_RESULT = '相合'
            } else {
              val.MATCH_RESULT = ''
            }
          }

          return val
        })
        this.listLoading = false
      },
      async submit() {
        if (this.bloodMatchTypePid === 2) {
          this.list = this.list.map((val) => {
            val.MATCH_RESULT = val.blood_match_types[0].MATCH_RESULT
            return val
          })
        }
        this.selectRows = this.list.filter((val) => {
          return val.MATCH_RESULT && val.blood_match_types
        })

        if (this.selectRows.length > 0) {
          const rows = this.selectRows.map((val) => {
            const val_child = val.blood_match_types[0]
            const FIRST_RESULT = this.getResult(val_child.FIRST_RESULT)
            const SECOND_RESULT = this.getResult(val_child.SECOND_RESULT)
            const AGGREGATION_INTENSITY = this.getResult(
              val_child.AGGREGATION_INTENSITY
            )
            const currentTime = getCurrentTime()
            let MATCH_DATE = '',
              STOP_DATE = '',
              INVAL_DATE = ''
            if (val.MATCH_RESULT === '相合') {
              INVAL_DATE = currentTime
              MATCH_DATE = val.MATCH_DATE || currentTime
            } else {
              STOP_DATE = currentTime
            }
            const BLOOD_MATCH_RESULT = {
              BLOOD_ID: val.BLOOD_ID,
              APPLY_NUM: val.APPLY_NUM,
              MATCH_SHEET_NUM: val.MATCH_SHEET_NUM,
              FIRST_RESULT: FIRST_RESULT || '',
              SECOND_RESULT: SECOND_RESULT || '',
              MATCH_DATE,
              INVAL_DATE,
              MATCH_RESULT: val.MATCH_RESULT || '',
              MATCH_OPERATOR: this.username,
              STOP_DATE,
              RESULT_DATE: currentTime,
              AGGREGATION_INTENSITY: AGGREGATION_INTENSITY || '',
              blood_match_types: val.blood_match_types,
              blood_match_type_id: this.bloodMatchTypePid,
              DAT: val.DAT,
            }
            if (+this.bloodMatchTypePid === 2) {
              delete BLOOD_MATCH_RESULT.DAT
            }
            return {
              BLOOD_MATCH_RESULT,
            }
          })

          let submitRows = []
          if (this.bloodMatchTypePid === 2) {
            submitRows = rows.filter((val) => {
              return val.BLOOD_MATCH_RESULT.AGGREGATION_INTENSITY
            })
          } else {
            submitRows = rows.filter((val) => {
              return val.BLOOD_MATCH_RESULT.FIRST_RESULT
            })
          }

          const result = {
            ArrayOfBLOOD_MATCH_RESULT: submitRows,
          }
          saveMatchResult(result).then((res) => {
            this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
            this.fetchData()
          })
        } else {
          this.$baseMessage(
            '未检测到有填写配血结果和子配血结果的记录，请核实后再提交',
            'error',
            'vab-hey-message-error'
          )
        }
      },
      getResult(value) {
        if (value) {
          if (['无凝集', '凝集'].includes(value)) {
            return value === '无凝集' ? '无凝集' : '凝集'
          }
          return value
        }
        return ''
      },
      handleRefresh() {
        this.fetchData()
      },
      handleChange(row, pRow, attr) {
        if (+row.blood_match_type_pid === 1) {
          if (row.FIRST_RESULT) {
            if (row.FIRST_RESULT === '无凝集') {
              if (attr === 'FIRST_RESULT' && !row.SECOND_RESULT) {
                row.SECOND_RESULT = '无凝集'
              }
              row.MATCH_RESULT = '相合'
            } else {
              row.MATCH_RESULT = '不相合'
            }
          }
          this.handleResultChange(row, pRow, attr)
        } else {
          if (row.AGGREGATION_INTENSITY) {
            if (row.AGGREGATION_INTENSITY === '阴性') {
              row.MATCH_RESULT = '相合'
            } else {
              row.MATCH_RESULT = '不相合'
            }
          }
        }
      },
      handleResultChange(row, pRow, attr) {
        if (row.MATCH_RESULT === '相合') {
          if (!attr && !row.SECOND_RESULT) {
            row.SECOND_RESULT = '无凝集'
          }
          if (!row.FIRST_RESULT) {
            row.FIRST_RESULT = '无凝集'
          }
          if (!row.AGGREGATION_INTENSITY) {
            row.AGGREGATION_INTENSITY = '阴性'
          }
        }
        const blood_match_types = pRow.blood_match_types
        if (
          blood_match_types.filter((val) => {
            return val.MATCH_RESULT === '相合'
          }).length === blood_match_types.length
        ) {
          pRow.MATCH_RESULT = '相合'
        }
        if (
          blood_match_types.filter((val) => {
            return val.MATCH_RESULT === '不相合'
          }).length === blood_match_types.length
        ) {
          pRow.MATCH_RESULT = '不相合'
        }
      },
      tableRowClassName({ row }) {
        return getMatchTransClass(row)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .pr8 {
    padding-right: 8px;
  }
</style>
